package com.tanhua.dubbo.api.impl;

import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.RecommendUserApi;
import com.tanhua.dubbo.api.VisitorsApi;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;


@Service(timeout = 100000000)
public class VisitorsApiImpl implements VisitorsApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private RecommendUserApi recommendUserApi;

    @Override
    // 第一次
    // db.visitors.find({userId:1}).sort({date:-1}).limit(5)
    public List<Visitors> queryVisitors(Long userId, int i) {
        Query query = new Query(Criteria.where("userId").is(userId));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(i);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return getVisitors(visitorsList);
    }

    @Override
    // 非第一次
    // db.visitors.find({userId:1,date:{$gt:1609922625750}})
    public List<Visitors> queryVisitors(Long userId, Long lastTime) {
        Query query = new Query(Criteria.where("userId").is(userId).and("date").gt(lastTime));
        query.with(Sort.by(Sort.Order.desc("date")));
        query.limit(5);
        List<Visitors> visitorsList = mongoTemplate.find(query, Visitors.class);
        return getVisitors(visitorsList);
    }

    /**
     * 抽取公共方法
     *
     * @param visitorsList
     * @return
     */
    private List<Visitors> getVisitors(List<Visitors> visitorsList) {
        if (visitorsList != null) {
            for (Visitors visitors : visitorsList) {
                // 查询每个访客的缘分值
                Long fateValue = recommendUserApi.queryScore(visitors.getUserId(), visitors.getVisitorUserId());
                visitors.setScore(fateValue);
            }
        }
        return visitorsList;
    }
}
